<template>
  <el-menu class="header" :default-active="activeMenu" mode="horizontal" @select="handleSelect">
    <hamburger v-if="screenWidth <= 992 && routeval != '/index'" id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container hamburgerFiexd" @toggleClick="toggleSideBar" />
    <!------------------------------ 左侧部分 ------------------------------>
    <div class="left">
      <el-menu-item v-for="(item, index) in topMenus" :key="'left' + index" v-show="index < Math.ceil(visibleNumber / 2)" :style="{ '--theme': theme }" :index="item.path">
        <!-- <svg-icon :icon-class="item.meta.icon" /> -->
        {{ item.meta.title }}
      </el-menu-item>
    </div>
    <!------------------------------ 项目标题 ------------------------------>
    <div class="center" @click="$router.push(router)">
      <img src="@/assets/images/logo.png" alt="">
      崂矿数字工厂
    </div>
    <!------------------------------ 右侧部分 ------------------------------>
    <div class="right">
      <el-menu-item v-for="(item, index) in topMenus" :style="{ '--theme': theme }" :index="item.path" :key="'right' + index" v-show="index >= Math.ceil(visibleNumber / 2) && index < visibleNumber">
        <!-- <svg-icon :icon-class="item.meta.icon" /> -->
        {{ item.meta.title }}
      </el-menu-item>
      <!--------- 顶部菜单超出数量折叠 --------->
      <el-submenu index="more" v-if="topMenus.length > visibleNumber" background-color="none">
        <template slot="title">
          更多
          <!-- <i class="el-icon-s-operation"></i> -->
        </template>
        <template v-for="(item, index) in topMenus">
          <el-menu-item :index="item.path" :key="index" v-if="index >= visibleNumber">
            <svg-icon :icon-class="item.meta.icon" />
            {{ item.meta.title }}
          </el-menu-item>
        </template>
      </el-submenu>
    </div>
    <!-- <img src="~@/assets/images/admin.png" alt="" @click="logout" class="info" /> -->
    <el-badge :value="infoNumber" class="info" @click="infoRouter" :max="99">
      <i class="el-icon-message" @click="infoRouter"></i>
    </el-badge>
    <!-- <el-dropdown>
      <el-button type="primary" @command="handleCommand">
        <img src="~@/assets/images/admin.png" alt="" class="logout" />
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click="logout">退出</el-dropdown-item>
        <el-dropdown-item>修改密码</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown> -->
    <el-dropdown @command="handleCommand">
      <img src="~@/assets/images/admin.png" alt="" class="logout" />
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="b">修改资料</el-dropdown-item>
        <el-dropdown-item command="a">退出</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <!-- <img src="~@/assets/images/admin.png" alt="" @click="logout" class="logout" /> -->
  </el-menu>
</template>

<script>
import Hamburger from "@/components/Hamburger"; /* 左侧是否隐藏按钮 */
import { mapGetters, mapState } from "vuex";
import { constantRoutes } from "@/router";
import fontSize from "@/modules/fontSize";
import { getUserNum } from "@/api/basic/message/info.js";
export default {
  components: { Hamburger },
  data() {
    return {
      // 顶部栏初始数
      visibleNumber: 8,
      // 是否为首次加载
      isFrist: false,
      // 当前激活菜单的 index
      currentIndex: undefined,
      screenWidth: null, //屏幕宽度
      routeval: null, //路由信息
      //警报信息
      infoNumber: "",
      timer: null,
    };
  },
  created() {
    // this.routeval = this.$route.path;
  },

  computed: {
    ...mapGetters(["sidebarRouters", "sidebar", "roles", "router"]),
    theme() {
      return this.$store.state.settings.theme;
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = [];
      this.routers.map((menu) => {
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
            topMenus.push(menu.children[0]);
          } else {
            topMenus.push(menu);
          }
        }
      });
      return topMenus;
    },
    // 所有的路由信息
    routers() {
      return this.$store.state.permission.topbarRouters;
     
    },
    // 设置子路由
    childrenMenus() {
      // console.log(this.routers)
      var childrenMenus = [];
      this.routers.map((router) => {
        for (var item in router.children) {
          if (router.children[item].parentPath === undefined) {
            if (router.path === "/") {
              router.children[item].path =
                "/redirect/" + router.children[item].path;
            } else {
              if (!this.ishttp(router.children[item].path)) {
                router.children[item].path =
                  router.path + "/" + router.children[item].path;
              }
            }
            router.children[item].parentPath = router.path;
          }
          childrenMenus.push(router.children[item]);
        }
      });
      return constantRoutes.concat(childrenMenus);
    },
    // 默认激活的菜单
    activeMenu() {
      const path = this.$route.path;
      // let activePath = this.routers[0].path;
      let activePath = "/index";
      if (path.lastIndexOf("/") > 0) {
        const tmpPath = path.substring(1, path.length);
        activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
      } else if ("/index" == path || "" == path) {
        if (!this.isFrist) {
          this.isFrist = true;
        } else {
          activePath = "/index";
        }
      }
      if (path == "/basic/messageinfo") {
        activePath = "";
      }
      // var routes = this.activeRoutes(activePath);
      // if (routes.length === 0) {
      //   activePath = this.currentIndex || this.routers[0].path;
      //   this.activeRoutes(activePath);
      // }
      return activePath;
    },
  },
  beforeMount() {
    window.addEventListener("resize", this.setVisibleNumber);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.setVisibleNumber);
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  watch: {
    $route: {
      handler(val, oldval) {
        this.routeval = val.path;
      },
      // 深度观察监听
      deep: true,
    },
  },
  mounted() {
    this.setVisibleNumber();
    this.activeMenus();
    this.getUserNum();
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.timer = setInterval(() => {
      this.getUserNum();
    }, 10000);
    //实时监听屏幕宽度
    // window.onresize = () => {
    //   return (() => {
    //     this.screenWidth = document.body.clientWidth;
    //   })();
    // };
  },
  methods: {
    handleCommand(e) {
      if (e == "a") {
        this.logout();
      } else {
        this.$router.push("/user/profile");
      }
    },
    //获取消息数量
    getUserNum() {
      getUserNum().then((res) => {
        if (res.code == 200) {
          this.infoNumber = res.number;
          if (this.infoNumber == 0) {
            this.infoNumber = "";
          }
        }
      });
    },
    //跳转信息页面
    infoRouter() {
      // console.log(111)
      this.$router.push("/basic/messageinfo");
    },
    toggleSideBar() {
      this.$store.dispatch("app/toggleSideBar");
    },
    //默认激活的菜单
    activeMenus() {
      const path = this.$route.path;
      let activePath = this.routers[0].path;
      var routes = this.activeRoutes(activePath, "onload");
      if (routes.length === 0) {
        activePath = this.currentIndex || this.routers[0].path;
        this.activeRoutes(activePath, "onload");
      }
      /* 刚进入页面时，默认跳转第一个路由 */
      let topMenus = this.topMenus;
      try {
        // if(path =="/index"){
        //   if (topMenus[0].children) {
        //     //有子级列表时执行
        //     this.$router.push(
        //       topMenus[0].children[0].path
        //     );
        //   } else {
        //     this.$router.push(topMenus[0].path);
        //   }
        // }

        // if (this.roles.includes("admin")) {
        //   this.$router.push("/");
        // } else {
        //   this.$router.push("/parcelIndex");
        // }
        this.$router.push(this.router);
      } catch (err) {
        return false;
      }
    },
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      // const width = document.body.getBoundingClientRect().width / 3;
      const width = document.body.getBoundingClientRect().width / 2.5;
      this.screenWidth = document.body.clientWidth;
      // this.visibleNumber = parseInt(width / 90);
      // this.visibleNumber = parseInt(width / 120);
    },
    // 菜单选择事件
    handleSelect(key, keyPath) {
      // console.log("点击菜单了", key);
      this.currentIndex = key;
      if (this.ishttp(key)) {
        // http(s):// 路径新窗口打开
        window.open(key, "_blank");
      } else if (key.indexOf("/redirect") !== -1) {
        // /redirect 路径内部打开
        if (this.roles.includes("admin")) {
          // this.$router.push("/");
          this.$router.push({ path: key.replace("/redirect", "") });
        } else {
          this.$router.push("/parcelIndex");
        }
      } else {
        // 显示左侧联动菜单
        if (key == "/index" || key == "/" || key == "/redirect/index") {
          // console.log(this.roles.includes("admin11"))
          // if (this.roles.includes("admin")) {
          //   this.$router.push("/");
          // } else {
          //   this.$router.push("/parcelIndex");
          // }
          this.$router.push("/");
        } else {
          this.activeRoutes(key, "handleSelect");
        }
      }
    },
    // 当前激活的路由
    activeRoutes(key, val) {
      var routes = [];
      if (this.childrenMenus && this.childrenMenus.length > 0) {
        this.childrenMenus.map((item) => {
          if (key == item.parentPath || (key == "index" && "" == item.path)) {
            routes.push(item);
          }
        });
        // console.log(this.childrenMenus)
      }
      // this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      // if (routes.length > 0) {
      //   if (val == "handleSelect") {
      //     //判断是点击还是第一步默认加载
      //     try {
      //       if (routes[0].children) {
      //         //有子级列表时执行
      //         this.$router.push(
      //           routes[0].path + "/" + routes[0].children[0].path
      //         );
      //       } else {
      //         this.$router.push(routes[0].path);
      //       }
      //     } catch (err) {
      //       return false;
      //     }
      //   } else {
      //     const str = this.$route.path.split("/"); /* 获取路由信息 */
      //     if (str.length <= 2) {
      //       this.$store.commit("SET_SIDEBAR_ROUTERS", []);
      //     }
      //   }
      // } else {
      //   this.$router.push(key);
      // }
      if (routes.length > 0) {
        this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
        if (val == "handleSelect") {
          //判断是点击还是第一步默认加载
          try {
            if (routes[0].children) {
              //有子级列表时执行
              this.$router.push(
                routes[0].path + "/" + routes[0].children[0].path
              );
            } else {
              this.$router.push(routes[0].path);
            }
          } catch (err) {
            return false;
          }
        } else {
          const str = this.$route.path.split("/"); /* 获取路由信息 */
          if (str.length <= 2) {
            this.$store.commit("SET_SIDEBAR_ROUTERS", []);
          }
        }
      }
      return routes;
    },
    ishttp(url) {
      return url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1;
    },
    //退出系统
    async logout() {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/index";
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss">
.header {
  width: 100%;
  height: 90px;
  background: url("~@/assets/images/headerBj.png") no-repeat !important;
  background-size: 100% 98% !important;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;

  .left,
  .right {
    width: 27%;
    display: flex;
    margin-top: -13px;
    justify-content: flex-start;
    align-items: center;
  }
  .left {
    justify-content: flex-end;
  }
  .center {
    width: 36%;
    cursor: pointer;
    // background: linear-gradient(#51bbff 0%, #8df3ff 100%);
    // font-size: 12px;
    font-size: 34px;
    font-family: PingFang SC Bold, PingFang SC Bold-Bold;
    font-weight: 700;
    text-align: center;
    color: #ffffff;
    height: 90px;
    position: relative;
    top: -5px;
    line-height: 80px;
    letter-spacing: 6px;
    text-shadow: 0px 5px 5px 0px rgba(0, 25, 110, 0.75);
    font-weight: 700;
    cursor: pointer;
    background: linear-gradient(0deg, #fff9c5 0%, #ffffff 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    // background: linear-gradient(0deg,#fff9c5 0%, #ffffff 100%);
    // font-size: 38px;
    font-family: Source Han Sans CN, Source Han Sans CN-Normal;
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 90px;
      margin-right: 30px;
    }
    // font-weight: bold;
    // text-align: left;
    // color: #ffffff;
    // line-height: 174px;
    // letter-spacing: 0.95px;
  }
  .logout {
    width: 28px;
    height: 28px;
    cursor: pointer;
    // right: -5%;
    margin-left:-10px;
    margin-top: -27px;
    position: absolute;
  }
  .info {
    width: 28px;
    height: 28px;
    cursor: pointer;
    right: 3%;
    margin-top: -25px;
    background: none;
    position: absolute;
    i {
      font-size: 23px;
      position: relative;
      top: -2px;
      color: rgba(212, 240, 255, 0.9);
    }
  }
}
.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 50px;
  line-height: 50px;
  margin: 0;
  border-bottom: 3px solid transparent;
  color: #999093;
  padding: 0 5px;
  margin: 0 10px;
}
.header {
  .el-submenu {
    float: left;
    height: 46px;
    font-size: 20px;
    margin: 0;
    border-bottom: 3px solid transparent;
    color: rgba(212, 240, 255, 0.8) !important;
    // padding: 0 5%;
    // margin: 0 10px;
    .el-submenu__title {
      color: rgba(212, 240, 255, 0.8) !important;
      font-size: 17px;
      i {
        color: #ffffff;
        font-size: 16px;
      }

      height: 50px;
      line-height: 35px;
      .el-submenu__icon-arrow {
        display: none;
      }

      &:hover {
        -webkit-text-shadow: rgb(28 140 255) 0 0 10px;
        -moz-text-shadow: rgb(28 140 255) 0 0 10px;
        -o-text-shadow: rgb(28 140 255) 0 0 10px;
        text-shadow: rgb(28 140 255) 0 0 10px;
        font-weight: bold;
        background: none;
      }
    }
  }
  @media screen and (max-width: 480px) {
    .el-submenu__title {
      font-size: 12px !important;
      padding: 0 25% !important;
      i {
        color: #ffffff;
        font-size: 12px !important;
      }
    }
  }
}

.el-menu--horizontal > .el-menu-item.is-active {
  border-bottom: 3px solid #{"var(--theme)"};
  color: #303133;
}
/* submenu item */
.el-menu--horizontal > .el-submenu .el-submenu__title {
  height: 50px !important;
  line-height: 50px !important;
}
.el-menu.el-menu--horizontal {
  border: none;
}
</style>
<style scoped lang='scss'>
.el-menu--horizontal .el-menu .el-menu-item,
.el-menu--horizontal .el-menu .el-submenu__title {
  background: rgba(31, 85, 132, 1) !important;
  border: 1px solid rgba(31, 85, 132, 0.9) !important;
  color: #cccccc !important;
  i,
  svg,
  path {
    color: #cccccc !important;
    stroke: #cccccc !important;
    fill: #cccccc !important;
  }
  &:hover {
    background-color: rgba(45, 173, 231, 0.9) !important;
    color: #ffffff !important;
  }
}
.hamburgerFiexd {
  width: 28px;
  height: 28px;
  position: absolute;
  margin-top: -18px;
  font-size: 20px;
  left: 0px;
  z-index: 100;
}
@media screen and (max-width: 480px) {
  .hamburgerFiexd {
    font-size: 16px;
    margin-top: -13.5px;
    left: -5px;
  }
}
</style>
<style >
.el-badge__content {
  /* padding: 3px; */
  border: none;
}
.header .el-dropdown {
  right: -10px;
}
</style>